package edu.stanford.prpl.app.prpltalk.android;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SimpleAdapter;
import edu.stanford.prpl.api.BlobResource;
import edu.stanford.prpl.app.prpltalk.PRPLTalk;
import edu.stanford.prpl.common.util.URIUtils;

public class SessionListActivity extends ListActivity {

	private static final String TAG = "SessionListActivity";

	private static final int JOIN_ID = Menu.FIRST;
	private static final int LIST_CONTACTS_ID = Menu.FIRST + 1;
	private static final int ACTIVITY_CHAT = 2;

	private static final String KEY_ID = "ID", KEY_OWNER = "Owner", KEY_RECP = "Recp", KEY_LDATE = "LDate";

	BlobResource[] resources;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.session_list_layout);
		this.populateList();
	}

	private void populateList() {

		int r_layout = -1;

		String[] from = null;
		int[] to = null;
		r_layout = R.layout.session_list_row;
		from = new String[] { KEY_ID, KEY_OWNER, KEY_RECP, KEY_LDATE };
		to = new int[] { R.id.session_id, R.id.session_owner, R.id.session_recp, R.id.session_last_modified };

		SimpleAdapter files = new SimpleAdapter(this, this.getSessionList(), r_layout, from, to);
		setListAdapter(files);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {

		switch (item.getItemId()) {
		case JOIN_ID: {

			if (this.getSelectedItemId() < 0)
				return true;

			BlobResource resource = resources[(int) this.getSelectedItemId()];

			// Create a new chat session
			String sessionId = PrPlTalkActivity.prplTalk.resourceURI2sessionId(resource.getURI());

			boolean joined = PrPlTalkActivity.prplTalk.joinSession(sessionId);

			Object[] recipients = resource.getMetaData(PRPLTalk.PROPERTY_RECIPIENT_URI);

			List<String> list = new ArrayList<String>();
			for (Object recp : recipients) {
				if (URIUtils.isIdentityURI(recp.toString()))
					list.add(URIUtils.getIdentityKey(recp.toString()));
				else
					list.add(recp.toString());
			}

			ChatSessionManager.getInstance().startChatSession(sessionId, list);
			Log.d(TAG, "Joining session (" + sessionId + ") with " + Arrays.toString(recipients));

			Intent i = new Intent();
			i.setClassName("edu.stanford.prpl.app.prpltalk.android", "edu.stanford.prpl.app.prpltalk.android.ChatPage");
			i.putExtra(ContactsPage.KEY_CHAT_SESSION_ID, sessionId);
			startActivityForResult(i, ACTIVITY_CHAT);
			return true;
		}
		case LIST_CONTACTS_ID: {
			Intent i = new Intent();
			i.setClassName("edu.stanford.prpl.app.prpltalk.android", "edu.stanford.prpl.app.prpltalk.android.ContactsPage");
			startActivityForResult(i, 'C');
			return true;
		}
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, JOIN_ID, 0, R.string.join).setIcon(R.drawable.chat);
		menu.add(0, LIST_CONTACTS_ID, 0, "Contacts").setIcon(R.drawable.add_contact);
		return result;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		boolean b = super.onKeyDown(keyCode, event);

		switch (keyCode) {
		case KeyEvent.KEYCODE_C: {
			Intent i = new Intent();
			i.setClassName("edu.stanford.prpl.app.prpltalk.android", "edu.stanford.prpl.app.prpltalk.android.ContactsPage");
			startActivityForResult(i, 'C');
			break;
		}

		}
		return b;
	}

	protected List<Map<String, String>> getSessionList() {

		List<Map<String, String>> list = new LinkedList<Map<String, String>>();

		this.resources = PrPlTalkActivity.prplTalk.getAllCommunicationResources();

		for (BlobResource resource : resources) {

			Object[] metadata = resource.getMetaData(PRPLTalk.PROPERTY_SESSION_ID_URI);
			String sid = (metadata.length > 0) ? metadata[0].toString() : "";
			metadata = resource.getMetaData(PRPLTalk.PROPERTY_RECIPIENT_URI);
			Object[] recipients = metadata;
			String text = new String();
			Map<String, String> m = new HashMap<String, String>();
			// m.put(KEY_ID, sid);
			m.put(KEY_ID, "S" + list.size());
			m.put(KEY_OWNER, resource.getOwner().getKey());
			m.put(KEY_RECP, "");// Arrays.toString(recipients));
			DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
			String date = df.format(resource.getLastModifiedDate().getTime());
			m.put(KEY_LDATE, date);
			list.add(m);
		}

		return list;
	}
}
